import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';

class UploadPage extends StatefulWidget {
  @override
  _UploadPageState createState() => _UploadPageState();
}

class _UploadPageState extends State<UploadPage> {
  String answer = '';
  String? fileName;
  double uploadProgress = 0.0;
  bool isUploading = false;

  void uploadFile() async {
    setState(() {
      isUploading = true;
      uploadProgress = 0.0;
    });

    // Simulating upload progress
    for (int i = 0; i <= 100; i++) {
      await Future.delayed(Duration(milliseconds: 50));
      setState(() {
        uploadProgress = i / 100;
      });
    }

    // After simulation, check for success or failure randomly
    if (uploadProgress >= 1.0) {
      Fluttertoast.showToast(msg: "上传成功！", toastLength: Toast.LENGTH_SHORT);
    } else {
      Fluttertoast.showToast(msg: "上传失败，请重试。", toastLength: Toast.LENGTH_SHORT);
    }

    setState(() {
      isUploading = false;
    });
  }

  Future<void> pickFile() async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['jpg', 'png', 'pdf'], // 仅允许图片和PDF文件
      allowMultiple: false,
    );

    if (result != null) {
      // 检查文件大小（例如限制为 5MB）
      if (result.files.single.size > 5 * 1024 * 1024) {
        Fluttertoast.showToast(msg: "文件过大，请选择小于5MB的文件。");
      } else {
        setState(() {
          fileName = result.files.single.name;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('答案与上传状态'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              onChanged: (value) {
                setState(() {
                  answer = value; // 实时预览
                });
              },
              decoration: InputDecoration(labelText: "输入您的答案"),
            ),
            SizedBox(height: 20),
            Text(
              "预览答案: $answer", // 实时预览显示
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),
            if (fileName != null) Text("选择的文件: $fileName"),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: pickFile,
              child: Text("选择文件"),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: isUploading ? null : uploadFile,
              child: Text(isUploading ? "上传中..." : "上传文件"),
            ),
            SizedBox(height: 20),
            LinearProgressIndicator(value: uploadProgress),
            SizedBox(height: 20),
            Text(
              isUploading ? "上传进度: ${(uploadProgress * 100).toStringAsFixed(0)}%" : "上传完成",
            ),
          ],
        ),
      ),
    );
  }
}